/* ***** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/LGPL 2.1/GPL 2.0

The contents of this file are subject to the Mozilla Public License Version 
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ 
Software distributed under the License is distributed on an "AS IS" basis, 
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.

The Original Code is the Ironsoft Kumquat.

The Initial Developer of the Original Code is
Ironsoft.
Portions created by the Initial Developer are Copyright (C) 2011
the Initial Developer. All Rights Reserved.

Contributor(s):
  Tomas de Priede <tdepriede@ironsoft.com.ar>

Alternatively, the contents of this file may be used under the terms of
either of the GNU General Public License Version 2 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead 
of those above. If you wish to allow use of your version of this file only 
under the terms of either the GPL or the LGPL, and not to allow others to 
use your version of this file under the terms of the MPL, indicate your 
decision by deleting the provisions above and replace them with the notice 
and other provisions required by the GPL or the LGPL. If you do not delete 
the provisions above, a recipient may use your version of this file under
 the terms of any one of the MPL, the GPL or the LGPL

 ***** END LICENSE BLOCK *****
 */

/**
 * File name: UserAccount.java
 *
 * Project name: Kumquat
 *
 * Created at: 12/10/2011
 *
 * Author: Tomiito
 */
package ar.com.ironsoft.kumquat.server.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.JDOCanRetryException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import ar.com.ironsoft.kumquat.server.persistence.PMF;
import ar.com.ironsoft.kumquat.server.persistence.cache.CacheSupport;
import ar.com.ironsoft.kumquat.server.persistence.cache.Cacheable;
import ar.com.ironsoft.kumquat.server.utils.Utils;
import ar.com.ironsoft.kumquat.shared.dto.UserAccountDTO;

/**
 * @author Tomiito
 * 
 */
@SuppressWarnings("serial")
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")
public class UserAccount implements Serializable, Cacheable {

	private static final Logger log = Logger.getLogger(Utils.class.getName());
	private static final int NUM_RETRIES = 5;

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Long id;

	@Persistent
	private String firstName;

	@Persistent
	private String lastName;

	@Persistent
	private String emailAddress;

	@Persistent
	private String password;

	@Persistent
	private Date lastLoginOn;

	@Persistent
	private Date lastActive;

	@Persistent
	private Date lastReported;

	public UserAccount() {
		super();
	}

	public UserAccount(String emailAddress, String password) {
		super();
		this.emailAddress = emailAddress;
		this.password = password;
	}

	public UserAccount(String firstName, String lastName, String emailAddress, String password) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.emailAddress = emailAddress;
		this.password = password;
	}

	public String getFullname() {
		return String.format("%s %s", firstName, lastName);
	}

	public static boolean changePassword(String emailAddress, String actualPassword, String newPassword) {

		PersistenceManager pm = PMF.getNonTransactionalPersistenceManager();
		UserAccount oneResult = null;

		Query q = pm.newQuery(UserAccount.class, "emailAddress == :emailAddress && password == :password");
		q.setUnique(true);
		boolean changed = true;
		try {

			oneResult = (UserAccount) q.execute(emailAddress, actualPassword);

			if (oneResult == null)
				changed = false;
			else {

				oneResult.password = newPassword;
				log.info("Updating password...");
				pm.makePersistent(oneResult);
				log.info("Creating a new password change log record entity...");
				pm.makePersistent(new PasswordChange(emailAddress, actualPassword, new Date()));
			}

		} catch (Exception e) {
			log.log(Level.WARNING, "The password could not be changed", e);
			throw new RuntimeException(e);
		} finally {
			pm.close();
		}
		return changed;
	}

	public static UserAccount findOrCreateUser(UserAccount user) {
		PersistenceManager pm = PMF.getTransactionalPersistenceManager();
		Transaction tx = null;
		UserAccount oneResult = null, detached = null;

		Query q = pm.newQuery(UserAccount.class, "emailAddress == :emailAddress");
		q.setUnique(true);

		// We use a transaction to prevent another process
		// from creating an user with same id

		try {
			for (int i = 0; i < NUM_RETRIES; i++) {
				tx = pm.currentTransaction();
				tx.begin();
				oneResult = (UserAccount) q.execute(user.emailAddress);
				if (oneResult != null) {
					log.info("User email already exists " + user.emailAddress.toString());
					detached = pm.detachCopy(oneResult);
				} else {
					log.info("UserAccount " + user.emailAddress + " does not exists, creating...");
					pm.makePersistent(user);
					detached = pm.detachCopy(user);
				}
				try {
					tx.commit();
					break;
				} catch (JDOCanRetryException e1) {
					if (i == (NUM_RETRIES - 1))
						throw e1;
				}
			}
		} catch (Exception e) {
			log.log(Level.WARNING, "The user could not be created or reached", e);
		} finally {
			if (tx.isActive())
				tx.rollback();
			pm.close();
			q.closeAll();
		}
		return detached;
	}

	public static UserAccountDTO toDTO(UserAccount user) {
		if (user == null)
			return null;

		UserAccountDTO accountDTO = new UserAccountDTO(user.emailAddress, user.getFullname(), user.id.toString());
		return accountDTO;
	}

	@Override
	public void addToCache() {
		CacheSupport.cachePut(this.getClass().getName(), id, this);
	}

	@Override
	public void removeFromCache() {
		CacheSupport.cacheDelete(this.getClass().getName(), id);
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmailAddress() {
		return emailAddress;
	}

	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}

	public Date getLastLoginOn() {
		return lastLoginOn;
	}

	public void setLastLoginOn(Date lastLoginOn) {
		this.lastLoginOn = lastLoginOn;
	}

	public Date getLastActive() {
		return lastActive;
	}

	public void setLastActive(Date lastActive) {
		this.lastActive = lastActive;
	}

	public Date getLastReported() {
		return lastReported;
	}

	public void setLastReported(Date lastReported) {
		this.lastReported = lastReported;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
